<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Service;

use Doctrine\ORM\EntityManager;
use Sales\Entity\Order;
use Shop\Common\ShopCommon;

class OrderManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加订单
     * @param array $data
     * @param $currency
     * @return Order
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addOrder(array $data, $currency)
    {
        $data['baseOrderAmount'] = $data['orderAmount'];
        $data['orderAmount'] = $data['orderAmount'] * $currency['rate'];
        $data['goodsAmount'] = $data['goodsAmount'] * $currency['rate'];
        $data['deliveryFee'] = $data['deliveryFee'] * $currency['rate'];

        $order = new Order();
        $order->valuesSet($data);
        $order->setOrderSn(ShopCommon::createOrderSn());
        $order->setCurrencyCode($currency['code']);
        $order->setCurrencySymbol($currency['symbol']);
        $order->setOrderWeightAmount($data['totalWeight']);
        $order->setShippingFee($data['deliveryFee']);
        $order->setOrderReturnType(0);
        $order->setOrderAddTime(time());

        $this->entityManager->persist($order);
        $this->entityManager->flush();

        return $order;
    }

    /**
     * 编辑订单
     * @param array $data
     * @param Order $order
     * @return Order
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editOrder(array $data, Order $order)
    {
        $order->valuesSet($data);
        $this->entityManager->flush();

        return $order;
    }

    /**
     * 编辑订单退货状态（是否有商品退货）
     * @param $returnType
     * @param $orderId
     */
    public function updateOrderReturnType($returnType, $orderId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(Order::class, 'o')->set('o.orderReturnType', ':orderReturnType')->setParameter('orderReturnType', $returnType)
            ->where('o.orderId = :orderId')->setParameter('orderId', $orderId);

        $qb->getQuery()->execute();
    }

    /**
     * 删除订单
     * @param Order $order
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteOrder(Order $order)
    {
        $this->entityManager->remove($order);
        $this->entityManager->flush();

        return true;
    }
}